// pages/favorite/favorite.js
const { safeGet } = require('../../utils/data-validator')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    favorites: [],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 10
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadFavorites();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log('收藏页面准备完成');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 每次显示页面时刷新数据
    this.refreshFavorites();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // 页面隐藏时的处理
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 页面卸载时的处理
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.refreshFavorites();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadFavorites();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的收藏店铺',
      path: '/pages/favorite/favorite'
    };
  },

  // 刷新收藏列表
  refreshFavorites() {
    this.setData({
      page: 1,
      favorites: [],
      hasMore: true
    });
    this.loadFavorites().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 加载收藏数据
  async loadFavorites() {
    if (this.data.loading) return;

    this.setData({ loading: true });

    try {
      // 先从本地存储读取收藏数据
      const localFavorites = wx.getStorageSync('favoriteStores') || [];
      
      // 如果本地没有收藏数据，使用模拟数据
      let allFavorites = localFavorites.length > 0 ? localFavorites : this.generateMockFavorites();
      
      // 补全数据结构
      allFavorites = allFavorites.map(item => this.completeFavoriteData(item));
      
      // 按收藏时间倒序排列
      allFavorites.sort((a, b) => new Date(b.favoriteTime) - new Date(a.favoriteTime));
      
      // 分页处理
      const startIndex = (this.data.page - 1) * this.data.pageSize;
      const endIndex = startIndex + this.data.pageSize;
      const currentPageData = allFavorites.slice(startIndex, endIndex);
      
      this.setData({
        favorites: this.data.page === 1 ? currentPageData : [...this.data.favorites, ...currentPageData],
        page: this.data.page + 1,
        hasMore: endIndex < allFavorites.length,
        loading: false
      });
      
      console.log('收藏数据加载完成:', {
        总数: allFavorites.length,
        当前页: currentPageData.length,
        是否还有更多: endIndex < allFavorites.length
      });
      
    } catch (error) {
      console.error('加载收藏失败:', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 补全收藏数据结构
  completeFavoriteData(item) {
    return {
      id: safeGet(item, 'id', Date.now()),
      name: safeGet(item, 'name', '未知商家'),
      description: safeGet(item, 'description', '暂无描述'),
      avatar: safeGet(item, 'avatar', '/images/default-store.png'),
      rating: safeGet(item, 'rating', 0),
      reviewCount: safeGet(item, 'reviewCount', 0),
      distance: safeGet(item, 'distance', '距离未知'),
      deliveryTime: safeGet(item, 'deliveryTime', '时间未知'),
      deliveryFee: safeGet(item, 'deliveryFee', 0),
      tags: safeGet(item, 'tags', []),
      isOpen: safeGet(item, 'isOpen', true),
      favoriteTime: safeGet(item, 'favoriteTime', new Date().toISOString()),
      ...item
    };
  },

  // 生成模拟收藏数据
  generateMockFavorites() {
    const favorites = [
      {
        id: 1,
        name: '麦当劳(王府井店)',
        description: '经典美式快餐，汉堡薯条',
        avatar: '/images/stores/mcdonalds.jpg',
        rating: 4.5,
        reviewCount: 1234,
        distance: '1.2km',
        deliveryTime: '25分钟',
        deliveryFee: 3,
        tags: ['快餐', '汉堡', '薯条'],
        isOpen: true,
        favoriteTime: '2024-01-15 14:30'
      },
      {
        id: 2,
        name: '肯德基(三里屯店)',
        description: '香脆炸鸡，美味可口',
        avatar: '/images/stores/kfc.jpg',
        rating: 4.3,
        reviewCount: 987,
        distance: '0.8km',
        deliveryTime: '20分钟',
        deliveryFee: 3,
        tags: ['快餐', '炸鸡', '汉堡'],
        isOpen: true,
        favoriteTime: '2024-01-10 16:45'
      },
      {
        id: 3,
        name: '星巴克(中关村店)',
        description: '精品咖啡，休闲时光',
        avatar: '/images/stores/starbucks.jpg',
        rating: 4.6,
        reviewCount: 756,
        distance: '2.1km',
        deliveryTime: '35分钟',
        deliveryFee: 5,
        tags: ['咖啡', '饮品', '甜点'],
        isOpen: false,
        favoriteTime: '2024-01-08 10:20'
      },
      {
        id: 4,
        name: '海底捞火锅(中关村店)',
        description: '优质火锅，贴心服务',
        avatar: '/images/stores/haidilao.jpg',
        rating: 4.8,
        reviewCount: 2156,
        distance: '1.5km',
        deliveryTime: '40分钟',
        deliveryFee: 6,
        tags: ['火锅', '川菜', '服务'],
        isOpen: true,
        favoriteTime: '2024-01-05 19:15'
      }
    ];

    return favorites;
  },

  // 跳转到店铺详情
  goToStore(e) {
    const store = e.currentTarget.dataset.store;
    wx.navigateTo({
      url: `/pages/store-detail/store-detail?id=${store.id}`
    });
  },

  // 取消收藏
  removeFavorite(e) {
    const store = e.currentTarget.dataset.store;
    
    wx.showModal({
      title: '取消收藏',
      content: `确定要取消收藏"${store.name}"吗？`,
      success: (res) => {
        if (res.confirm) {
          try {
            // 从当前列表中移除
            const favorites = this.data.favorites.filter(item => item.id !== store.id);
            this.setData({ favorites });
            
            // 从本地存储中移除
            const localFavorites = wx.getStorageSync('favoriteStores') || [];
            const updatedFavorites = localFavorites.filter(item => item.id !== store.id);
            wx.setStorageSync('favoriteStores', updatedFavorites);
            
            // 通知全局数据更新
            const app = getApp();
            if (app && app.onFavoriteChange) {
              app.onFavoriteChange('remove', store);
            }
            
            console.log('取消收藏成功:', store.name);
            
            wx.showToast({
              title: '已取消收藏',
              icon: 'success'
            });
            
          } catch (error) {
            console.error('取消收藏失败:', error);
            wx.showToast({
              title: '取消收藏失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 加载更多
  loadMore() {
    if (!this.data.hasMore || this.data.loading) return;
    this.loadFavorites();
  },

  // 去逛逛
  goShopping() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空方法，用于阻止事件冒泡
  }
})